//
//  MapTrajectory.m
//  carcareIOS
//
//  Created by wr on 15/6/30.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "MapTrajectory.h"
#import "TraAnnotationView.h"
#import "MapReGeocodeSimple.h"

typedef NS_ENUM(NSInteger,Line_Color_Type) {
    Line_Color_Type_Red = 20,//速度0-20 标记红色线
    Line_Color_Type_Orange = 40,//速度20-40 标记橙色线
    Line_Color_Type_Yellow = 60,//速度40-60 标记黄色线
    Line_Color_Type_Green = 70,//速度60以上 标记绿色线
};

@interface MapTrajectory()<MAMapViewDelegate>
{
    CLLocationCoordinate2D * _runningCoords;
}
@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, copy) NSArray * gpsArr;

@property (nonatomic , strong) NSMutableArray * speedColors;

@property (nonatomic, strong) MAMultiPolyline * polyline;

@property (nonatomic, strong) NSTimer * trajectoryTimer;

@property (nonatomic, strong) TraAnnotation * traAnnotation;

@property (nonatomic, strong) MapReGeocodeSimple * mapSimple ;

@property (nonatomic) CGFloat timerTime;

//纪录地图的region 用于后期更改地图region时   更改nstimer 时间
@property (nonatomic , assign) MACoordinateRegion mapOldRegion;

//用来判断是否是开始动画状态的bool
@property (nonatomic ) BOOL isAnimation;

//用来判断star or end 默认为yes  进入star 变为no no为end终点
@property (nonatomic )BOOL isStarOrEnd;

//用来记录是不是第一次播放 ，如果不是第一次播放 值为yes 那么时间变长 并设置其可是范围为初始值
@property (nonatomic)BOOL isNotOnePlay;

//根据速度 线的颜色类型
@property (nonatomic , assign) Line_Color_Type lineColorType;

@property (nonatomic , assign) Map_Type mapType;

@property (nonatomic , assign) CLLocationCoordinate2D centerCoordinate;

@end

@implementation MapTrajectory

- (instancetype)initWithType:(Map_Type)type withModel:(OneDriveModel *)model
{
    self = [super init];
    if (self) {
        self.mapType = type;
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        self.mapView.delegate = self;
        
        self.gpsArr = model.gpss;
        [self createBeginAndEndAnnotation];
        [self createLineTrajecory];
        
        if(model.gpsTypes.count > 0 && self.mapType == Map_Type_CanTouch){
            [self createTypeAnnotationWithTypes:model.gpsTypes];
        }
        
        self.currentIndex = 0;
        _isNotOnePlay = NO;
        
        self.timerTime = 0.01;
        self.isAnimation = NO;
        
    }
    return self;
}
#pragma  mark - 区域改变
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate
{
    if(self.mapDidTouch) self.mapDidTouch();
}
#pragma mark -

-(TraAnnotation *)traAnnotation{
    if (!_traAnnotation) {
        _traAnnotation = [[TraAnnotation alloc] init];
    }
    return _traAnnotation;
}

#pragma mark -

- (void)createBeginAndEndAnnotation
{
    TraBeginEndAnnotation *beginAnnotation = [[TraBeginEndAnnotation alloc] init];
    WayGpsInfoModel *beginModel = [self.gpsArr firstObject];
    beginAnnotation.status = GPS_BEGIN;
    [beginAnnotation setCoordinate:beginModel.coordinate];
    
    TraBeginEndAnnotation *endAnnotation = [[TraBeginEndAnnotation alloc] init];
    WayGpsInfoModel *endModel = [self.gpsArr lastObject];
    endAnnotation.status = GPS_END;
    [endAnnotation setCoordinate:endModel.coordinate];
    
    NSArray *tmp = @[beginAnnotation, endAnnotation];
    [self.mapView addAnnotations:tmp];
    
    _isStarOrEnd = YES;
}

-(void)createTypeAnnotationWithTypes:(NSArray *)type{
    NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:type.count];
    [type enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TraTypeAnnotation *pointA = [[TraTypeAnnotation alloc] init];
        pointA.model = obj;
        [tmp addObject:pointA];
    }];
    [self.mapView addAnnotations:tmp];
}

- (void)createLineTrajecory
{
    self.speedColors = [NSMutableArray arrayWithCapacity:self.gpsArr.count];
    NSMutableArray * indexes = [NSMutableArray arrayWithCapacity:self.gpsArr.count];
    
//    NSMutableArray * cllocationCoordinate2DArray = [NSMutableArray arrayWithCapacity:self.gpsArr.count];
//    CLLocationCoordinate2D coordinates[self.gpsArr.count];
     _runningCoords = (CLLocationCoordinate2D *)malloc(self.gpsArr.count * sizeof(CLLocationCoordinate2D));
    for (int index = 0; index < self.gpsArr.count; index++)
    {
        @autoreleasepool {
            WayGpsInfoModel * model = self.gpsArr[index];
            _runningCoords[index].latitude = model.lat;
            _runningCoords[index].longitude = model.lng;
            
            [self.speedColors addObject:[self loadSpeedColor:model.SPEED]];
            [indexes addObject:@(index)];

        }
    }
    _polyline = [MAMultiPolyline polylineWithCoordinates:_runningCoords count:self.gpsArr.count drawStyleIndexes:indexes];
    
}
- (void) reloadPolyLine
{
    [self.mapView addOverlay:_polyline];
    const CGFloat screenEdgeInset = self.mapType == Map_Type_NoTouch ? 5 : 100;
    UIEdgeInsets inset = UIEdgeInsetsMake(screenEdgeInset + 25, screenEdgeInset, screenEdgeInset, screenEdgeInset);
    [self.mapView setVisibleMapRect:_polyline.boundingMapRect edgePadding:inset animated:NO];
}
- (UIColor *)loadSpeedColor:(NSInteger)speed
{
    if (speed <= Line_Color_Type_Red) {
        return COLOR_HEXSTRING(@"#f74342");
    }else if(speed <= Line_Color_Type_Orange)
    {
        return COLOR_HEXSTRING(@"#ffc21c");
    }else if(speed <= Line_Color_Type_Yellow)
    {
        return COLOR_HEXSTRING(@"#5fcc37");
    }else if(speed > Line_Color_Type_Yellow)
    {
        return COLOR_HEXSTRING(@"#16a0f1");
    }
    return nil;
}
-(void)showLocation
{
    [self.mapView setCenterCoordinate:self.centerCoordinate animated:YES];
}
#pragma mark - MAMapView Delegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[TraTypeAnnotation class]] ) {//急加速急减速急转弯
        
        static NSString *reuseIndetifier = @"type";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (!annotationView)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        
        TraTypeAnnotation *anno = (TraTypeAnnotation *)annotation;
        CGFloat viewR = 5;
        annotationView.layer.cornerRadius = viewR;
        annotationView.layer.masksToBounds = YES;
        
        switch (anno.model.type) {
            case GPS_DOWN:
                //                annotationView.image = [ImageHelper imageWithSolidColor:COLOR_HEXSTRING(@"#47A9EB") size:annotationViewSize];
                annotationView.image = ImageNamed(@"TraSpeedDownImage");
                break;
            case GPS_UP:
                annotationView.image = ImageNamed(@"TraSpeedUpImage");
                break;
            case GPS_TURN:
                break;
            case GPS_SHAKE:
                break;
            default:
                break;
        }
        annotationView.centerOffset = CGPointMake( 0 , -15);
        [annotationView setFrame:CGRectMake(0, 0, 25, 30)];
        annotationView.enabled = NO;
        return annotationView;
    }else if ([annotation isKindOfClass:[TraAnnotation class]]){//
        
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        TraAnnotationView *annotationView = (TraAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[TraAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        annotationView.annotation = annotation;
        annotationView.status = ((WayGpsInfoModel *)self.gpsArr[self.currentIndex]).beginEnd;
        switch (annotationView.status) {
            case GPS_BEGIN:
            case GPS_END :
            {
                NSString * imageStr = (_isStarOrEnd ? @"restaurantStar" : @"restaurantEnd");
                annotationView.image = [UIImage imageNamed:imageStr];
                _isStarOrEnd = NO;
            }
                break;
            case GPS_ONWAY:
                annotationView.image = [UIImage imageNamed:@"restaurantWay"];
                break;
            default:
                break;
        }
        // 设置为NO，用以调用自定义的calloutView
        annotationView.canShowCallout = NO;
        //设置中⼼心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0,-27);
        annotationView.frame = CGRectMake(0, 0, 54, 54);
        //如果是起始位置 不显示气泡
        annotationView.selected = YES;
        annotationView.userInteractionEnabled = YES;
        
        return annotationView;
    }else if ([annotation isKindOfClass:[TraBeginEndAnnotation class]]){//
        static NSString *reuseIndetifier = @"BeginAndEnd";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (!annotationView)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        switch (((TraBeginEndAnnotation *)annotation).status) {
            case GPS_BEGIN:
                annotationView.image = [UIImage imageNamed:@"restaurantStar"];
                break;
            case GPS_END:
                annotationView.image = [UIImage imageNamed:@"restaurantEnd"];
                break;
            default:
                break;
        }
        if (self.mapType == Map_Type_NoTouch) {
            annotationView.centerOffset = CGPointMake( 0 , -15);
            [annotationView setFrame:CGRectMake(0, 0, 20.75, 30)];
            
        }else
        {
            annotationView.centerOffset = CGPointMake( 0 , - 25);
            [annotationView setFrame:CGRectMake(0, 0, 34.5, 50)];
            
        }
        annotationView.enabled = NO;
        return annotationView;
    }
    return nil;
}

#pragma mark - 继续在ViewController.m文件中，实现<MAMapViewDelegate>协议中的mapView:viewForOverlay:回调函数，设置折线的样式。示例代码如下

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if (overlay == self.polyline)
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:(MAMultiPolyline *)overlay];
        
        polylineRenderer.lineWidth = (self.mapType == Map_Type_NoTouch ? 4.0f : 8.0f)
        ;
        polylineRenderer.strokeColors = self.speedColors;
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
    }
    return nil;
}

- (MACoordinateRegion)loadVisibleMapRect:(NSMutableArray *)coordinates
{
    float minLat = 0.0;
    float maxLat = 0.0;
    float minLon = 0.0;
    float maxLon = 0.0;
    for (int index = 0 ; index < coordinates.count; index ++) {
        if (index == 0) {
            minLat = [[coordinates[0] firstObject] floatValue];
            maxLat = [[coordinates[0] firstObject] floatValue];
            minLon = [[coordinates[0] lastObject] floatValue];
            maxLon = [[coordinates[0] lastObject] floatValue];
        }else{
            minLat = MIN(minLat, [[coordinates[index] firstObject] floatValue]);
            maxLat = MAX(maxLat, [[coordinates[index] firstObject] floatValue]);
            minLon = MIN(minLon, [[coordinates[index] lastObject] floatValue]);
            maxLon = MAX(maxLon, [[coordinates[index] lastObject] floatValue]);
        }
    }
    CLLocationCoordinate2D centCoor;
    centCoor.latitude = (CLLocationDegrees)((maxLat + minLat) * 0.5f);
    centCoor.longitude = (CLLocationDegrees)((maxLon + minLon) * 0.5f);
    MACoordinateSpan span;
    //设置跨度
    span.latitudeDelta = (maxLat - minLat) * 0.03;
    span.longitudeDelta = (maxLon - minLon) * 0.03;
    //得出坐标区域
    MACoordinateRegion region= MACoordinateRegionMake(centCoor, span);
    
    return region;
    
}
- (void)dealloc
{
    if (_runningCoords)
    {
        free(_runningCoords);
    }
}


@end
